/**
 * created by 江心才子, 2020/4/27 0027
 * Copyright (c) 2020, 270628297@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.wyl.viewmodel

import androidx.lifecycle.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 项目名称：LearnAndroid_Jetpack
 * 创建人：江心才子
 * 创建时间：2020-04-27 10:08
 * 内容描述：
 * 修改说明：
 */
class MyViewModel : ViewModel() {
    private val _count = MutableLiveData(0)

    val count: LiveData<String> = _count.map {
        it.toString()
    }

    val name = MutableLiveData("")

    fun addCount(i: Int) {
        val value = _count.value!!
        _count.value = value + i
    }

    private lateinit var increaseJob: Job

    fun startIncrease() {
        if (this::increaseJob.isInitialized && !increaseJob.isCancelled) return

        increaseJob = viewModelScope.launch {
            while (true) {
                delay(1000)
                addCount(1)
            }
        }
    }

    fun stopIncrease() {
        increaseJob.cancel()
    }
}